export function clearIOSBounce () {
  let [startX, startY] = [0, 0]
  // 需要响应touch 事件的容器添加 class="tu-need-scroll'即可
  const scrollBoxes = Array.from(document.querySelectorAll('.tu-need-scroll'))

  document.body.removeEventListener('touchstart', touchstart)
  document.body.removeEventListener('touchmove', touchmove)

  function touchstart (e) {
    if (!scrollBoxes.length) { return }
    startX = e.touches[0].pageX
    startY = e.touches[0].pageY
  }

  function touchmove (e) {
    if (!scrollBoxes.length) { return e.preventDefault() }
    let node = isChildTarget(e.target, scrollBoxes)
    const moveX = e.touches[0].pageX
    const moveY = e.touches[0].pageY
    const top = node && node.scrollTop
    const ch = node && node.clientHeight
    const sh = node && node.scrollHeight

    const isVertical = Math.abs(moveY - startY) > Math.abs(moveX - startX)
    const isOnSide = (top === 0 && moveY > startY) || (top + ch === sh && moveY < startY)
    if (!node) {
      e.preventDefault()
    } else if (isVertical && isOnSide) {
      e.preventDefault()
    }
  }

  document.body.addEventListener('touchstart', touchstart, {
    passive: false
  })
  document.body.addEventListener('touchmove', touchmove, {
    passive: false
  })
}

function isChildTarget(currTarget, scrollBoxes) {
  let parentNode = currTarget
  if (currTarget && scrollBoxes) {
    while (parentNode) {
      let node = scrollBoxes.find(el => el === parentNode)
      if (node) { return node }
      parentNode = parentNode.parentNode
    }
  }
  return null
}
